import { ofetch } from 'ofetch'
import {toast} from "@/@core/components/app-sonner/libs"
import { destr } from 'destr'
import { router } from '@/plugins/1.router/index'
import { useStore } from "@/stores/index";
import { cookieRef } from '@/@layouts/stores/config';

export const $api = ofetch.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  
  async onRequest({ options }) {
    const store = useStore();
    if (options.headers && options.headers.loading) {
      store.showLoading()
    }
    const accessToken = localStorage.getItem("accessToken") || sessionStorage.getItem("accessToken")
    const contentLang = cookieRef('content-language','zh_CN')
    if (accessToken) {
      options.headers = {
        ...options.headers,
        'Content-Language': contentLang.value,
        Authorization: `Bearer ${accessToken}`,
        clientId: 'e5cd7e4891bf95d1d19206ce24a7b32e',
      }
    }
    // options.headers = { ...options.headers, 'Content-Language': 'zh_CN' }
  },
  async onRequestError({ request, error }) {
    const store = useStore();
    store.hideLoading()
    console.log('request', request)
    console.log('error', error)
  },
  async onResponse({ response,options }) {
    const store = useStore();
    store.hideLoading()
    if (response.status === 200) {
      if (response.url.includes('image')) {
        return
      }
      // 二进制数据则直接返回
    if (options.responseType === 'blob' || options.responseType === 'arraybuffer') {
      return response._data;
    }
      let parsedData = null
      try {
        parsedData = destr(response._data)
      }
      catch (error) {
        console.error(error)
      }
      if (parsedData.code === 401) {
        toast('登陆状态已过期,请重新登录',{
          cardProps: {
            color: 'error',
          },
          prependIcon: 'tabler-ban'
        })
        router.replace({
          path: '/login',
          query: {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath || '/')
          }})
        return Promise.reject(new Error('登陆状态已过期,请重新登录'))
      }else if (parsedData.code !== 200) {
        toast(parsedData.msg,{
          cardProps: {
            color: 'error',
          },
          prependIcon: 'tabler-ban'
        })
        return Promise.reject(new Error(parsedData.msg));
      }
    }
  },
  async onResponseError({ response}) {
    const store = useStore();
    store.setToastPosition('top-center')
    store.hideLoading()
    let {statusText } = response

    if (statusText == 'Internal Server Error') {
      statusText = '后端接口连接异常';
    } else if (statusText.includes('timeout')) {
      statusText = '系统接口请求超时';
    } else if (statusText.includes('Request failed with status code')) {
      statusText = '系统接口' + statusText.substr(statusText.length - 3) + '异常';
    }

    toast(statusText,{
      cardProps: {
        color: 'error',
      },
      prependIcon: 'tabler-ban'
    })

    return Promise.reject(new Error(response))
  },
})

export const $fetchList = (url,options)=>{
  if (options.method === 'GET' && options.query) {
    let requestUrl = url + '?' + tansParams(options.query);
    url = requestUrl.slice(0, -1);
    options.query = {};
    return $api(url,options)
  }
}


export const $loading = (url,options,loading=true)=>{
  options.headers = {...options.headers,loading:loading}
  return $api(url,options)
}
